import React, { memo, useEffect, useRef, useState } from 'react'
import { ScorllViewWarp } from './style'
import IconRight from '@/assets/svg/icon_right'

const ScorllView = memo(props => {
  const soltRef = useRef()

  let [showRight, setShowRight] = useState(false)
  let [showLeft, setShowLeft] = useState(false)
  let [scorllGap, setScorllGap] = useState(0)
  useEffect(() => {
    let scrollWidth = soltRef.current.scrollWidth
    let clientWidth = soltRef.current.clientWidth
    setScorllGap(scrollWidth - clientWidth)
    setShowRight(scrollWidth > clientWidth)
  }, [props.children])

  const [curIndex, setCurIndex] = useState(0)
  function changePosition(direction) {
    let nextIndex = direction === 'left' ? curIndex - 1 : curIndex + 1
    let ele = soltRef.current.children[nextIndex]
    let distance = ele.offsetLeft
    soltRef.current.style.transform = `translateX(${-distance}px)`
    setCurIndex(nextIndex)
    setShowRight(scorllGap > distance)
    setShowLeft(distance > 0)
  }

  return (
    <ScorllViewWarp>
      {showLeft && (
        <div className="arrow left-arr" onClick={() => changePosition('left')}>
          <IconRight></IconRight>
        </div>
      )}

      {showRight && (
        <div className="arrow right-arr" onClick={() => changePosition('right')}>
          <IconRight></IconRight>
        </div>
      )}
      <div className="scorll">
        <div className="slot" ref={soltRef}>
          {props.children}
        </div>
      </div>
    </ScorllViewWarp>
  )
})

export default ScorllView
